<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
use League\OAuth2\Server\Exception\OAuthServerException;
use Log;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class AuthenticateApi
{
    use AuthenticatesUsers;

    public function handle($request, Closure $next)
    {
        $user = Auth::guard('api')->user();
        if (empty($user)) {
            return response()->json([
                'errCode' => 401,
                'errMsg' => 'token Unauthorized'
            ], 401);
        }
        if ($user->code !== $request->get('userID') ) {
            return response()->json([
                'errCode' => 401,
                'errMsg' => 'token invalid'
            ], 401);
        }
        try {
            if (!Auth::guard('api')->check()) {
                return response()->json([
                    'errCode' => 404,
                    'errMsg' => 'user not found'
                ], 404);
            }
        } catch (UnauthorizedHttpException $e) {
            return response()->json([
                'errCode' => 401,
                'errMsg' => 'token Unauthorized'
            ], 401);
        }catch (OAuthServerException $e) {
            return response()->json([
                'errCode' => 401,
                'errMsg' => 'token invalid'
            ], 401);
        }
        return $next($request);
    }
}

